import mongoose from 'mongoose'
import fs from 'fs'
import { resolve } from 'path'
import config from '../config'
const models = resolve(__dirname, '../database/schema')

// let env = process.env.NODE_ENV || 'development'
// let dbUrl = 'mongodb://root:zxhd520/sea'
// if (env === 'development') {
//   dbUrl = 'mongodb://localhost/sea'
// }

fs.readdirSync(models)    // 同步的读入模型文件
  .filter(file => ~file.search(/^[^\.].*\.js$/))    // 过滤后轴不是js的文件
  .forEach(file => require(resolve(models, file)))    // 循环require文件

const User = mongoose.model('User')

export const database = app => {
  mongoose.set('debug', true)
  mongoose.connect(config.db, { useNewUrlParser: true })
  mongoose.connection.on('disconnected', () => {    // 当断开自动连接
    mongoose.connect(config.db)
  })
  mongoose.connection.on('error', err => {    // 出错信息
    console.error(err)
  })
  mongoose.connection.on('open', async () => {   // 成功链接回调函数
    console.log('成功链接', config.db)
    let user = await User.findOne({
      email: 'lulu@qq.com'
    }).exec()
    if (!user) {
      console.log('写入管理员')
      user = new User({
        email: 'lulu@qq.com',
        password: 'lulu',
        role: 'admin'
      })

      await user.save()
    }
  })
}
